package com.aerozhonghuan.logisticsmall.utils.permisson;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;

import com.aerozhonghuan.foundation.base.BaseActivity;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.framework.base.MyAppliation;
import com.aerozhonghuan.logisticsmall.widget.CustomDialog;

/**
 * Created by zzw on 2018/3/29.
 */

public class PermissionRequestUtils extends BaseActivity {

    private static final String TAG = PermissionRequestUtils.class.getName();
    // 返回setResult requestCode
    public static final int PERMISSIONS_GRANTED = 1113;

    // 请求权限requestCode
    private static final int PERMISSION_REQUEST_CODE = 1114;
    // 权限参数
    private static final String EXTRA_PERMISSIONS = "com.aerozhonghuan.fax.station.permission.extra_permission";

    // 是否需要系统权限检测
    private boolean isRequireCheck;
    //是否开启权限
    public static boolean isCheckSuccess = false;

    // 启动当前权限页面的公开接口
    public static void startActivityForResult(Activity activity, int requestCode, String... permissions) {
        Intent intent = new Intent(activity, PermissionRequestUtils.class);
        intent.putExtra(EXTRA_PERMISSIONS, permissions);
        ActivityCompat.startActivityForResult(activity, intent, requestCode, null);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent() == null || !getIntent().hasExtra(EXTRA_PERMISSIONS)) {
            throw new RuntimeException("PermissionsActivity需要使用静态startActivityForResult方法启动!");
        }

        isRequireCheck = true;
        if (isRequireCheck) {
            String[] permissions = getPermissions();
            if (PermissionCheckUtils.lacksPermissions(MyAppliation.getApplication(), permissions)) {
                LogUtil.d(TAG, "请求权限onCreate");
                // 请求权限
                requestPermissions(permissions);
            } else {
                // 全部权限都已获取
                allPermissionsGranted();
            }
        } else {
            isRequireCheck = true;
        }
    }

    // 返回传递的权限参数
    private String[] getPermissions() {
        return getIntent().getStringArrayExtra(EXTRA_PERMISSIONS);
    }

    // 请求权限兼容低版本
    private void requestPermissions(String... permissions) {
        if (customDialog != null) {
            customDialog.dismiss();
        }
        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

    // 全部权限均已获取
    private void allPermissionsGranted() {
        isCheckSuccess = true;
        EventBusManager.post(new PermissionEvent(isCheckSuccess));
        setResult(PERMISSIONS_GRANTED);
        finish();
    }

    /**
     * 用户权限处理,
     * 如果全部获取, 则直接过.
     * 如果权限缺失, 则提示Dialog.
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
            isRequireCheck = true;
            allPermissionsGranted();
        } else {
            isRequireCheck = false;
            String message = "";
            if (permissions.length == 1 && permissions[0].contains("ACCESS_FINE_LOCATION")) {
                message = "请允许我们访问您的位置信息权限，否则程序将不能正常运行";
            } else if (permissions.length == 1 && permissions[0].contains("READ_EXTERNAL_STORAGE")) {
                message = "请允许我们访问您的内存卡权限，否则程序将不能正常运行";
            } else if (permissions.length == 1 && permissions[0].contains("READ_PHONE_STATE")) {
                message = "请允许我们访问您的手机信息权限，否则程序将不能正常运行";
            } else if (permissions.length == 1 && permissions[0].contains("CAMERA")) {
                message = "请允许我们访问您的照相机权限，否则程序将不能正常运行";
            } else if (permissions.length == 3) {
                message = "请允许我们访问您的位置信息、内存卡、手机信息权限，否则程序将不能正常运行";
            }
            LogUtil.d(TAG, "onRequestPermissionsResult()");
            showMissingPermissionDialog(message);
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1112) {
            LogUtil.d(TAG, "PErmissiononActivityResult()=" + !isRequireCheck + !PermissionCheckUtils.checkPerisson(this, getPermissions()) + isCheckSuccess);
            if (!PermissionCheckUtils.checkPerisson(this, getPermissions()) && !isRequireCheck) {
                isRequireCheck = false;
                String message = "";
                if (getPermissions().length == 1 && getPermissions()[0].contains("ACCESS_FINE_LOCATION")) {
                    message = "请允许我们访问您的位置信息权限，否则程序将不能正常运行";
                } else if (getPermissions().length == 1 && getPermissions()[0].contains("READ_EXTERNAL_STORAGE")) {
                    message = "请允许我们访问您的内存卡权限，否则程序将不能正常运行";
                } else if (getPermissions().length == 1 && getPermissions()[0].contains("READ_PHONE_STATE")) {
                    message = "请允许我们访问您的手机信息权限，否则程序将不能正常运行";
                } else if (getPermissions().length == 1 && getPermissions()[0].contains("CAMERA")) {
                    message = "请允许我们访问您的照相机权限，否则程序将不能正常运行";
                } else if (getPermissions().length == 3) {
                    message = "请允许我们访问您的位置信息、内存卡、手机信息权限，否则程序将不能正常运行";
                }
                showMissingPermissionDialog(message);
                return;
            } else {
                isRequireCheck = true;
                allPermissionsGranted();
                return;
            }
        }
    }

    // 含有全部的权限
    private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    // 显示缺失权限提示
    private CustomDialog customDialog = null;

    private void showMissingPermissionDialog(String message) {
        if (customDialog == null) {
            customDialog = new CustomDialog(this, "提示", message, "", "设置");
        }
        customDialog.setCancelable(false);
        customDialog.setOnDiaLogListener(new CustomDialog.OnDialogListener() {
            @Override
            public void dialogPositiveListener() {

            }

            @Override
            public void dialogNegativeListener() {
                customDialog.dismiss();
                BrandUtils.settingPermissionActivity(PermissionRequestUtils.this);
                if(Build.MANUFACTURER.equals("HUAWEI")){
                    finish();
                }
            }
        });
        customDialog.showDialog();
    }

}
